package org.ling.xuan.pannel;

import cn.hutool.core.util.StrUtil;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBTextArea;
import com.intellij.ui.components.JBTextField;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class SearchFilePanel extends JBPanel {

    private JBTextField regText;
    private JBTextField replaceKeyWords;
    private JBTextField targetKeyWords;
    private JBTextArea textArea;


    public SearchFilePanel() {
        setLayout(new GridLayout(4, 2, 10, 10));
        regText = new JBTextField(30);
        regText.setText("Sources.*?\\.java");
        replaceKeyWords = new JBTextField(30);
        replaceKeyWords.setText("/Sources/");
        targetKeyWords = new JBTextField(30);
        targetKeyWords.setText("D:/Sources/");
        textArea = new JBTextArea(20,250);
        add(new JBLabel("正则:"));
        add(regText);
        add(new JBLabel("替换关键词:"));
        add(replaceKeyWords);
        add(new JBLabel("目标关键词:"));
        add(targetKeyWords);
        add(new JBLabel("修改内容:"));
        add(textArea);
    }

    public List<String> getFileList() {
        List<String> result =  new ArrayList<>();
        String ss = textArea.getText();
        String p = regText.getText();
        Pattern pattern = Pattern.compile(p, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(ss);
        while (matcher.find()) {
            String s = matcher.group();
            s=s.replace("\r\n","\n");
            s = s.replace("\n","");
            s = s.replace("\\","/");
            result.add("/"+s);
        }
        if(StrUtil.isNotBlank(replaceKeyWords.getText())){
            String target = "";
            if(targetKeyWords.getText()!=null){
                target = targetKeyWords.getText();
            }
            String finalTarget = target;
            result = result.stream().map(s-> s= s.replace(replaceKeyWords.getText(), finalTarget)).collect(Collectors.toList());
        }
        return result;
    }
}
